<template>
    <enjoy-drawer :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="14vh" width="956px" append-to-body :fullscreen="fullscreen">
        <div class="drawer-content">
            <div class="btnGroup">
                <el-button icon="el-icon-user" v-if="type == 2" type="primary" size="small" @click="addUser">{{$t('userManage.addUser')}}</el-button>
                <el-button icon="el-icon-delete" v-if="type == 2" size="mini" class="deleteitemBtn" @click="handleRemove">{{$t('ncr.batchDelete')}}</el-button>
            </div>
            <el-table stripe :data="dialogForm.typeList" class="edit-table" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <!--          序号-->
                <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center" />
                <!--          姓名-->
                <el-table-column label="姓名" align="left" prop="userName" />

                <!--          部门-->
                <el-table-column label="部门" align="left" prop="deptName" />

                <!--          工号-->
                <el-table-column label="登录名称/工号" align="left" prop="workNumber" />
                <!--          接替人名称-->
                <el-table-column label="接替人名称" align="left" prop="replaceMan" />
                <!--          状态-->
                <!--        <el-table-column label="状态" align="left" prop="status" />-->
                <el-table-column v-if="type == 2" :label="$t('public.opera')" fixed="right" align="center" width="100">
                    <template slot-scope="scope">
                        <div class="action-wrap">
                            <table-body-btn type="gwedit" name="替换人" @click.native="handleUpdate(scope.row)" v-hasPermi="['tenant:post:edit']" />
                            <table-body-btn type="gwdelete" :name="$t('public.delete')" @click.native="handleDelete(scope.row)" v-hasPermi="['tenant:post:remove']" />
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
        </div>

        <div slot="footer">
            <el-button @click="$emit('update:visible',false)" icon="el-icon-close" size="small">{{$t('public.close')}}</el-button>
        </div>
        <enjoy-user-tree-dialog :visible.sync="userDialogVisible" :single="isSingle" :title="$t(`systemTitle.${!isSingle?'chooseUser':'selectSuccessor'}`)" @change="handlerDialogChange"></enjoy-user-tree-dialog>

    </enjoy-drawer>
</template>

<script>
// import {listAllFlawProjectMessage } from "@/api/basic/gaugeMessage";
// import { addFlawProject, updateFlawProject, listAllMaxFlaw, listMinFlaw} from "@/api/basic/flawProject";
import {addQmsUser, delQmsUser, geTreplace, listGroupUser,} from '@/api/system/userGroup'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'
import EnjoyDrawer from '@/components/EnjoyDrawer'
import EnjoyUserTreeDialog from '@/components/EnjoyUserTreeDialog'
// import { listALLMaterialType } from "@/api/basic/materialtype";

export default {
    name: 'flaw-drawer',
    components: {
        EnjoySelectUser,
        EnjoySelectDeptTree,
        FileUploadInput,
        EnjoyDrawer,
        EnjoyUserTreeDialog,
    },
    dicts: [
        'NYIQC_FLAW_TYPE', //缺陷类型
    ],
    props: {
        value: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    watch: {
        visible(val) {
            if (val) {
                this.getList()
            }
        },
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set(val) {
                this.$emit('update:visible', val)
            },
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title = '新增用户组'
            }
            if (type == 2) {
                title = '编辑用户组'
            }
            if (type == 3) {
                title = '查看用户组'
            }

            return title
        },
    },
    data() {
        return {
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            factoryOptions: undefined,
            userDialogType: 0,
            userDialogVisible: false,
            dialogForm: { typeList: [] },
            queryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            total: 0,
            // 表单校验
            rules: {
                maxFlawName: [
                    {
                        required: true,
                        message: this.$t('formValidation.bigDefectCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                flawType: [
                    {
                        required: true,
                        message: '缺陷类型不能为空',
                        trigger: 'blur',
                    },
                ],
                minFlawName: [
                    {
                        required: true,
                        message: '小缺陷名称不能为空',
                        trigger: 'blur',
                    },
                ],
                materialType: [
                    {
                        required: true,
                        message: this.$t('formValidation.materialNameCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
            },
            isSingle: false,
            ids: [],
            names: [],
        }
    },
    methods: {
        getList() {
            this.queryParams.groupId = this.value.id
            listGroupUser(this.queryParams).then((res) => {
                if (res.code == 200 && res.rows) {
                    // this.dialogForm = {...this.value,...res.rows[0]}
                    console.log(res.rows)
                    this.dialogForm.typeList = res.rows
                    this.total = res.total
                }
            })
        },
        addUser() {
            this.userDialogVisible = true
            this.userDialogType = 0
            this.isSingle = false
        },
        /** 发起提交 */
        submitForm: function () {
            this.$refs.detailForm.validate((valid) => {
                let action = this.type == 1 ? addFlawProject : updateFlawProject
                if (valid) {
                    this.loading = true
                    action(this.dialogForm).then(
                        (res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess('操作成功!')
                                this.$emit('update:visible', false)
                            }
                        },
                        (err) => {
                            this.loading = false
                        }
                    )
                }
            })
        },
        handleClose(done) {
            this.$emit('update:visible', false)
        },
        //设备模糊查询
        deviceRemoteMethod(val, cb) {
            console.log(val)
            listAllFlawProjectMessage({ deviceName: val }).then((res) => {
                this.deviceOptions = res.data.map((i) => i.deviceName)
                cb(res.data)
            })
        },
        handleDeviceSelect(e) {
            this.dialogForm.deviceName = e.deviceName
            this.dialogForm.gaugeType = e.gaugeType
            this.$refs.deviceName.$emit('el.form.blur')
        },
        handleDeviceBlur(e) {
            const { deviceOptions, dialogForm } = this
            if (!deviceOptions.includes(dialogForm.deviceName)) {
                this.dialogForm.deviceName = ''
            }
        },

        handleExpireTime(e) {
            console.log(e)
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        materialRemoteMethod(val, cb) {
            listALLMaterialType({ typeName: val }).then((res) => {
                this.materialOptions = res.data.map((i) => i.typeName)
                cb(res.data)
            })
        },
        handleMaterialSelect(e) {
            this.dialogForm.materialMiddle = e.materialMiddle
            this.$refs.materialMiddle.$emit('el.form.blur')
        },
        handleMaterialBlur(e) {
            const { materialOptions, dialogForm } = this
            if (!materialOptions.includes(dialogForm.materialMiddle)) {
                this.dialogForm.materialMiddle = ''
            }
        },
        flawMaxRemoteMethod(val, cb) {
            listAllMaxFlaw({ maxFlawName: val }).then((res) => {
                this.materialOptions = res.data.map((i) => i.typeName)
                cb(res.data)
            })
        },
        handleFlawMaxBlur(e) {
            this.dialogForm.materialMiddle = e.materialMiddle
            this.$refs.materialMiddle.$emit('el.form.blur')
        },
        handleFlawMaxSelect(e) {
            const { materialOptions, dialogForm } = this
            this.dialogForm.maxFlawId = e.maxFlawId
            if (!materialOptions.includes(dialogForm.maxFlawName)) {
                this.dialogForm.maxFlawName = ''
            }
        },
        handleAdd() {
            this.dialogForm.typeList.push({})
        },
        handleUpdate(row) {
            this.userDialogVisible = true
            this.userDialogType = row.id
            this.isSingle = true
        },
        handleRemove() {
            if (!this.ids.length) {
                this.$modal.msgWarning('请选择用户!')
                return
            }
            this.handleDelete()
        },
        handleDelete(row) {
            const ids = (row && row.id) || this.ids
            const names = (row && row.userName) || this.names
            this.$modal
                .confirm('是否确认删除用户名为"' + names + '"的数据项？')
                .then(function () {
                    return delQmsUser(ids)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('deptManage.delSuc'))
                })
                .catch(() => {})
        },
        handleFlawTypeChange() {},
        handlerDialogChange(e) {
            const { userDialogType } = this
            if (userDialogType == 0) {
                // addQmsUser({deptId:e.deptId,deptName:e.deptName,groupId:this.queryParams.groupId,userId:e.userId,userName:e.userName}).then(res=>{
                let params = []
                e.forEach((i) => {
                    params.push({
                        deleteFlag: i.deleteFlag,
                        deptId: i.deptId,
                        deptName: i.deptName,
                        fileId: i.fileId,
                        groupId: this.queryParams.groupId,
                        id: i.id,
                        params: i.params,
                        remark: i.remark,
                        replaceId: i.replaceId,
                        replaceMan: i.replaceMan,
                        searchValue: i.searchValue,
                        userId: i.userId,
                        userName: i.userName,
                        workNumber: i.loginName,
                    })
                })
                addQmsUser(params).then((res) => {
                    if (res.code == 200) {
                        this.getList()
                    }
                })
            } else if (userDialogType) {
                geTreplace({
                    id: userDialogType,
                    replaceId: e.userId,
                    replaceMan: e.userName,
                }).then((res) => {
                    this.getList()
                })
            }
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id)
            this.names = selection.map((item) => item.userName)
        },
    },
}
</script>

<style scoped>
.table-add {
    text-align: center;
    font-size: 12px;
    color: #666;
    padding: 7px;
    border: 1px solid #e3e8ee;
    border-top: 0;
    cursor: pointer;
}
.table-add:hover {
    color: #004d8c;
}
.edit-table {
    margin-top: 10px;
}
.edit-table ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 0;
}
.drawer-content {
    padding: 10px 20px;
}
</style>
